package com.mqb.n4;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * @author mqb
 * @date 2021/4/19 20:59
 */
@Slf4j(topic = "c.ExerciseSell")
public class ExerciseSell {
    public static void main(String[] args) throws InterruptedException {
        // 模拟多人买票
        TicketWindow window = new TicketWindow(1000);

        // 卖出的票数统计
        List<Integer> amountList = Collections.synchronizedList(new ArrayList<>(2000));

        // 所有线程的集合
        List<Thread> threadList = new ArrayList<>(2000);

        // 模拟2000人来买票
        for (int i = 0; i < 2000; i++) {
            Thread thread = new Thread(() -> {
                int amount = window.sell(randomAmount());
                /*try { Thread.sleep(randomAmount()); } catch (InterruptedException e) { e.printStackTrace(); }*/
                amountList.add(amount);
            });
            threadList.add(thread);
            thread.start();
        }

        // 等待 2000 个线程结束
        for (Thread thread : threadList) {
            thread.join();
        }

        // 统计卖出票数和剩余票数
        log.debug("余票数量：{}", window.getCount());
        log.debug("卖出的票数：{}", amountList.stream().mapToInt(i -> i).sum());
    }

    // Random 线程安全
    static Random random = new Random();

    // 模拟买票张数 1-5
    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }
}

// 售票窗口
class TicketWindow {
    private int count;

    public TicketWindow(int count) {
        this.count = count;
    }

    // 获取余票
    public int getCount() {
        return count;
    }

    // 售票
    public synchronized int sell(int amount) {
        if (this.count >= amount) {
            this.count -= amount;
            return amount;
        }
        return 0;
    }
}
